﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DistributedClient
{
    public partial class Form1 : Form
    {
        private BroadcastListener bcastListener;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bcastListener = new BroadcastListener(12345);
            bcastListener.Start();
            bcastListener.BroadcastReceived += receiveBroadcast;
        }

        private delegate void DoAddDelegate(string i);
        private void DoAdd(string i)
        {
            if (listBox1.InvokeRequired)
            {
                DoAddDelegate dad = new DoAddDelegate(DoAdd);
                this.Invoke(dad, i);
            }
            else
            {
                if (listBox1.Items.Contains(i)) { return; }
                listBox1.Items.Add(i);
            }
        }

        private void receiveBroadcast(object sender, BroadcastReceivedEventArgs e)
        {
            DoAdd(e.EndPoint.ToString());
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            bcastListener.Stop();
        }
    }
}
